package com.cloud.logger.zchain.zchainserver.service;

import com.cloud.logger.zchain.core.common.util.DateUtil;
import com.cloud.logger.zchain.zchainserver.base.GlobalConstants;
import com.cloud.logger.zchain.zchainserver.entity.AngelaLoggerProject;
import com.cloud.logger.zchain.zchainserver.entity.ProjectUserRelation;
import com.cloud.logger.zchain.zchainserver.entity.propertyenum.UserStatusEnum;
import com.cloud.logger.zchain.zchainserver.entity.vo.AngelaLoggerProjectBugVo;
import com.cloud.logger.zchain.zchainserver.mongo.AngelaEntityRepository;
import com.cloud.logger.zchain.zchainserver.mongo.AngelaProjectNodeRepository;
import com.cloud.logger.zchain.zchainserver.mongo.AngelaProjectRepository;
import com.cloud.logger.zchain.zchainserver.mongo.ProjectUserRelationRepository;
import com.cloud.logger.zchain.zchainserver.util.GlobalMap;
import com.cloud.logger.zchain.zchainserver.util.LoginUserThreadLocal;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 浙江卓锐科技股份有限公司
 *
 * @author zhengyt
 * @create 2017/12/22
 * @description
 */
@Service
public class MainService {

    @Resource
    private ProjectUserRelationRepository userRelationRepository;

    @Resource
    private AngelaProjectRepository angelaProjectRepository;

    @Resource
    private AngelaProjectNodeRepository angelaProjectNodeRepository;

    @Resource
    private AngelaEntityRepository angelaEntityRepository;

    private static String TRUE_FLAG = "1";

    public List<AngelaLoggerProjectBugVo> findProjectTree(String id){
        Sort sort = new Sort(Sort.Direction.DESC, "createdDate");
        List<AngelaLoggerProject> projects = angelaProjectRepository.findByParentNode(id, sort);

        String token = LoginUserThreadLocal.getCurrentUser();
        String userType = (String) GlobalMap.getUserMap(token).get(GlobalConstants.USER_STATUS);
        //去除没权限项目
        if(UserStatusEnum.simple.getName().equals(userType) && projects != null && projects.size()!= 0){
            String userId = (String) GlobalMap.getUserMap(token).get(GlobalConstants.ID);
            List<ProjectUserRelation> userRelationList = userRelationRepository.findByUserId(userId);
            ConcurrentHashMap map = new ConcurrentHashMap();
            for(ProjectUserRelation userRelation : userRelationList){
                map.put(userRelation.getProjectId(),TRUE_FLAG);
            }

            Iterator it = projects.iterator();
            while (it.hasNext()){
                AngelaLoggerProject obj = (AngelaLoggerProject)it.next();
                if(!TRUE_FLAG.equals(map.get(obj.getId()))){
                    it.remove();
                }
            }
        }

        List<AngelaLoggerProjectBugVo> projectBugVos = new ArrayList<>();

        Date startTime = DateUtil.getDayStart(new Date());
        for(AngelaLoggerProject project:projects){
            //vo赋值
            AngelaLoggerProjectBugVo vo = new AngelaLoggerProjectBugVo();
            BeanUtils.copyProperties(project, vo);
            long offProjectNum = angelaProjectNodeRepository.countByCodeAndStatus(project.getCode(),"on");
            long allProjectNum = angelaProjectNodeRepository.countByCode(project.getCode());
            long todayBugs= angelaEntityRepository.countByProjectAndCreateTimeAfterAndAlarmLevelNot(project.getCode(),
                    startTime,0);
            long todayLogs= angelaEntityRepository.countByProjectAndCreateTimeAfter(project.getCode(),
                    startTime);
            vo.setTodayBugs(todayBugs);
            vo.setTotalBugs(todayLogs);
            vo.setStatusStr("("+allProjectNum+"/"+offProjectNum+")");
            projectBugVos.add(vo);
        }

        return projectBugVos;
    }

    public List<AngelaLoggerProject> findCompany(){
        Sort sort = new Sort(Sort.Direction.DESC, "createdDate");
        List<AngelaLoggerProject> projects = angelaProjectRepository.findByParentNode("-1",sort);

        //修改部分
        String token = LoginUserThreadLocal.getCurrentUser();
        String userType = (String) GlobalMap.getUserMap(token).get(GlobalConstants.USER_STATUS);
        ConcurrentHashMap map = getAuthorityMap();
        Iterator it = projects.iterator();
        while (it.hasNext()){
            AngelaLoggerProject project = (AngelaLoggerProject)it.next();
            project.setParentNode(project.getId());
            List<AngelaLoggerProject> children = angelaProjectRepository.findByParentNode(project.getId(), sort);

            //验证权限部分
            if(UserStatusEnum.simple.getName().equals(userType) && children !=null && children.size() != 0){

                Iterator childerIterator = children.iterator();
                while (childerIterator.hasNext()){
                    AngelaLoggerProject childrenProject = (AngelaLoggerProject)childerIterator.next();
                    if(!TRUE_FLAG.equals(map.get(childrenProject.getId()))){
                        childerIterator.remove();
                    }
                }

            }

        }

        for(AngelaLoggerProject project:projects){
            List<AngelaLoggerProject> children = angelaProjectRepository.findByParentNode(project.getId(), sort);
            long offCount = 0;
            long allCount = 0;
            for(AngelaLoggerProject p :children){
                offCount += getOffProject(p);
                allCount += getAllProject(p);
            }
            String proStatus = allCount +"/"+offCount;
            project.setStatusStr("("+proStatus+")");
        }

        return projects;
    }

    private long getOffProject(AngelaLoggerProject project){
        return angelaProjectNodeRepository.countByCodeAndStatus(project.getCode(),"on");
    }

    private long getAllProject(AngelaLoggerProject project){
        return angelaProjectNodeRepository.countByCode(project.getCode());
    }

    private ConcurrentHashMap getAuthorityMap(){
        String token = LoginUserThreadLocal.getCurrentUser();
        String userType = (String) GlobalMap.getUserMap(token).get(GlobalConstants.USER_STATUS);
        List<ProjectUserRelation> userRelationList = null;
        ConcurrentHashMap map = null;
        if(UserStatusEnum.simple.getName().equals(userType)) {
            String userId = (String) GlobalMap.getUserMap(token).get(GlobalConstants.ID);
            userRelationList = userRelationRepository.findByUserId(userId);
            map = new ConcurrentHashMap();
            for(ProjectUserRelation userRelation : userRelationList){
                map.put(userRelation.getProjectId(),TRUE_FLAG);
            }
        }
        return map;
    }

}